import { makeAutoObservable, runInAction } from 'mobx'
import { fetchEvaluateDetail, submitEvaluate } from '../api'
import { delLocalStorage, getLocalStorage, setLocalStorage } from '@/storage'
import type { Answer, Question, QuestionAnswer, StorageAnswer } from './interface'
import { history } from 'umi'
import { QuestionTypeEnum } from './enum'
// import { YesNo } from '@/constant/enum'

export class Store {
    /** 班级ID */
    private _GroupID: number
    /** 评估表ID */
    private _EvaluateID: number
    /** 表单ID */
    private _ListID: number

    /** 题号 */
    no: number = 0
    /** 评估表数据 */
    evaluateData: { name: string } | undefined
    /** 题目 */
    questions: Question[] = []
    /** 答案 */
    answers: Answer[] = []

    constructor(groupId: number, evaluateId: number, listId: number) {
        makeAutoObservable(this)
        this._GroupID = groupId
        this._EvaluateID = evaluateId
        this._ListID = listId
        this._initData()
        this._initAnswer()
    }

    /** 初始化题目信息 */
    private _initData = async () => {
        const { data } = await fetchEvaluateDetail(this._EvaluateID, this._GroupID)
        runInAction(() => {
            this.evaluateData = data
            this.questions = data.questionArr
        })
    }

    /** 初始化上次未提交的答案 */
    private _initAnswer = () => {
        if (!this._ListID) return
        const storageAnswer = getLocalStorage('QUALITY_EVALUATE') as StorageAnswer
        console.log('init answer => ', storageAnswer)
        if (storageAnswer?.id === this._ListID) {
            this.answers = storageAnswer.answers
        }
    }

    /** 获取题目信息（题号、是否必填、是否回答状态） */
    get getQuestionList() {
        return this.questions.map((item, index) => ({
            no: index,
            isNeedAnswer: item.is_answer,
            answered: (() => {
                const answeredQuestionIds = this.answers.map(it => it.question_id)
                const getQuestionAnswer = (id: number) =>
                    this.answers.find(it => it.question_id === id)
                const currentAnswer = this.answers.find(it => it.question_id === item.id)

                if ([QuestionTypeEnum.Rate, QuestionTypeEnum.TeacherRate].includes(item.category)) {
                    // 评分题是否已回答
                    return (item.answer as QuestionAnswer[]).every(
                        itemAnswer =>
                            answeredQuestionIds.includes(itemAnswer.id) &&
                            Number(getQuestionAnswer(itemAnswer.id)?.result ?? 0) > 0,
                    )
                }

                if (item.category === QuestionTypeEnum.QA) {
                    // 问答题是否已回答
                    return currentAnswer && currentAnswer.result.toString().trim() !== ''
                }

                if (item.category === QuestionTypeEnum.MultiChoice) {
                    // 多选题是否已回答
                    return currentAnswer && (currentAnswer.result as string[] | number[]).length > 0
                }

                if (item.category === QuestionTypeEnum.SingleChoice) {
                    // 单选题是否已回答
                    return currentAnswer !== undefined
                }

                return false
            })(),
        }))
    }

    /** 是否为第一题 */
    get isFirstQuestion() {
        return this.no === 0
    }

    /** 是否为最后一题 */
    get isLastQuestion() {
        return this.no === this.questions.length - 1
    }

    /** 获取当前问题 */
    get currentQuestion() {
        if (this.questions.length === 0) return undefined
        return this.questions[this.no]
    }

    /** 获取当前问题对应的答案 */
    get currentAnswer() {
        return this.answers.find(item => item.question_id === this.currentQuestion?.id)
    }

    /** 全部题目是否已答题 */
    get isAllAnswered() {
        if (this.questions.length === 0) return false
        // return this.answers.length === this.questions.length
        return this.getQuestionList.every(item => item.answered)
    }

    /** 是否允许提交报告(所有必填题目已回答) */
    // get isAllowSubmit() {
    //     return this.getQuestionList
    //         .filter(item => item.isNeedAnswer === YesNo.Yes)
    //         .every(item => item.answered)
    // }

    /** 获取指定题目的回答结果 */
    getQuestionResult(id: number) {
        return this.answers.find(item => item.question_id === id)?.result
    }

    /**
     * 回答题目
     * @param id 题目ID
     * @param result 结果
     * @returns
     */
    updateAnswer = (id: number, result: Answer['result']) => {
        if (!this.currentQuestion) return
        let tmpAnswers = this.answers.filter(item => item.question_id !== id)
        tmpAnswers.push({
            question_id: id,
            result: result,
        })
        this.answers = tmpAnswers
        // 缓存答案防止页面刷新后数据丢失
        setLocalStorage('QUALITY_EVALUATE', {
            id: this._ListID,
            answers: this.answers,
        } as StorageAnswer)
    }

    /** 切换题目 */
    switchQuestion = (no: number) => {
        this.no = no
    }
    /** 下一题 */
    nextQuestion = () => {
        if (this.isLastQuestion) return
        this.no++
    }
    /** 上一题 */
    prevQuestion = () => {
        if (this.isFirstQuestion) return
        this.no--
    }

    submitAnswer = async () => {
        await submitEvaluate(this._GroupID, this._EvaluateID, this._ListID, this.answers)
        // 删除答案缓存
        delLocalStorage('QUALITY_EVALUATE')
        history.goBack()
    }
}
export default Store
